package com.wk.worksetter.view

import android.content.pm.PackageInfo
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.wk.worksetter.R
import com.wk.worksetter.adapter.AppInfoAdapter

/**
 * @author peng
 * @date 2021/1/28
 * 说明
 */
class AppsBottomDialog(
    private val packageInfos: List<PackageInfo>?,
    private val appIconWithPackage: MutableMap<String, Drawable?>?
) : BottomSheetDialogFragment() {

    private var chosenCallback: OnChosenCallback? = null
    private lateinit var mAdapter: AppInfoAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL,R.style.AppBottomSheet)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val contentView = layoutInflater.inflate(R.layout.dialog_apps_list, container, false)
        initContentView(contentView)
        return contentView
    }

    override fun onStart() {
        super.onStart()
        (view?.parent as View?)?.let {
            it.setBackgroundColor(Color.RED)
            val layoutparams = it.layoutParams as CoordinatorLayout.LayoutParams
            val behavior = layoutparams.behavior as BottomSheetBehavior<View>
            layoutparams.height = getPeekHeight()
            it.layoutParams = layoutparams
            behavior.peekHeight = getPeekHeight()
            behavior.state = BottomSheetBehavior.STATE_EXPANDED
        }
    }

    private fun initContentView(contentView: View) {
        val rvApps = contentView.findViewById<RecyclerView>(R.id.rv_apps)
        val closeBtn = contentView.findViewById<TextView>(R.id.close)
        closeBtn.setOnClickListener {
            dismissAllowingStateLoss()
        }
        mAdapter = AppInfoAdapter(packageInfos,appIconWithPackage).apply {
            setOnItemClickListener { adapter, _, position ->
                chosenCallback?.onChosen(adapter.getItem(position) as PackageInfo)
            }
        }
        rvApps.adapter = mAdapter

    }

    private fun getPeekHeight(): Int {
        return requireActivity().display?.height?.times(0.75)?.toInt() ?: 0
    }

    fun setOnChosenCallback(callback: OnChosenCallback){
        chosenCallback = callback
    }

    interface OnChosenCallback{
        fun onChosen(info:PackageInfo)
    }
}